package com.pickgliss.render2d.vo
{
	import com.pickgliss.utils.StringUtils;
	
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;

	public class MapItem implements IReadWriteAble
	{
		public static var ID_COUNTER:int = 0;
		public var source:*;
		public var width:int = -1;
		public var height:int = -1;
		public var visible:Boolean = true;
		public var name:String = "";
		public var index:int = 0;
		public static var Index:int = 9;
		public static const NUMBER_COUNT:int = 4;
		public var matrix:Matrix = new Matrix();
		public var id:uint;
		
		public function MapItem():void
		{
			id = ID_COUNTER++;
		}
		
		public function setDefaultName():void
		{
			if(source is String)
			{
				name = StringUtils.getFileNameFromUrl(source);
			}else
			{
				name = "Object "+StringUtils.getFixNumberString(Index,NUMBER_COUNT);
				Index++;
			}
		}
		
		public function set x(value:int):void
		{
			matrix.tx = value;
		}
		
		public function get x():int
		{
			return matrix.tx;
		}
		
		public function set y(value:int):void
		{
			matrix.ty = value;
		}
		
		public function get y():int
		{
			return matrix.ty;
		}
		
		public static function createMapItemFromPath(path:String):MapItem
		{
			if(path == null || path=="")return null;
			var item:MapItem = new MapItem();
			item.source = path;
			item.setDefaultName();
			return item;
		}
		
		private var _rect:Rectangle;
		public function get rect():Rectangle
		{
			if(_rect == null)_rect = new Rectangle();
			_rect.x = x;
			_rect.y = y;
			_rect.width = width;
			_rect.height = height;
			return _rect;
		}
		
		public function toBytearray():ByteArray
		{
			var result:ByteArray = new ByteArray();
			result.writeUTF(String(source));
			result.writeInt(width);
			result.writeInt(height);
			result.writeUTF(name);
			result.writeInt(matrix.a);
			result.writeInt(matrix.b);
			result.writeInt(matrix.c);
			result.writeInt(matrix.d);
			result.writeInt(matrix.tx);
			result.writeInt(matrix.ty);
			return result;
		}
		
		public function readFromBytearray(b:ByteArray):void
		{
			source = b.readUTF();
			width = b.readInt();
			height = b.readInt();
			name = b.readUTF();
			matrix.a = b.readInt();
			matrix.b = b.readInt();
			matrix.c = b.readInt();
			matrix.d = b.readInt();
			matrix.tx = b.readInt();
			matrix.ty = b.readInt();
		}
	}
}